import React from 'react';
import { Button, Modal, Radio, Form, message } from 'antd';
import './index.less';
import axios from 'axios';
import copy from 'copy-to-clipboard';
import Tips from '../../Tips/index';
import { connect } from 'react-redux';
import statuscode from '../../statuscode/index';
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
class Invite extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 1,
      disabled: '',
      invitation: '',
      update: 0
    };
  }
  copyUrl = (url) => {
    copy(url);
    message.success('复制成功，如果失败，请在输入框内手动复制.');
  };
  componentWillMount() {
    this.ismounted = true;
  }
  componentWillUnmount() {
    this.ismounted = false;
  }

  componentWillUpdate(nextprops, nextstate) {
    var openStatus = nextprops.invitationdata ? nextprops.invitationdata.openStatus : '';
    var invitation = nextprops.invitationdata ? nextprops.invitationdata.invitation : '';
    if (this.props.update == 1 && this.state.update != 1) {
      const disabled = (openStatus === 0) ? '' : 'disabled';
      this.setState({
        disabled: disabled,
        invitation: invitation,
        update: 1
      });
    }
    if (nextprops == this.props || nextstate == this.nextstate) return false;
    const disabled = (openStatus === 0) ? '' : 'disabled';
    this.setState({
      disabled: disabled,
      invitation: invitation
    });
  }
  InviteCode = () => {
    const Token = localStorage.getItem('token');
    this.setState({
      message: 'loading'
    });
    const _this = this;
    var networkName = this.props.invitationdata ? this.props.invitationdata.networkName : this.props.changeNetwork;
    var data = {
      orgId: this.props.changeOrgid,
      networkName: networkName
    };
    axios.post('/api/block/network/createInvitation', data, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token,
      }
    })
      .then(function (response) {
        var code = response.data.code;
        var message = statuscode[code];
        if (_this.ismounted) {
          if (statuscode[response.data.code] == undefined) code = '500';
          if (code == 200) {
            _this.setState({
              invitation: response.data.data.invitation,
              message: message
            }, () => {
              setTimeout(() => {
                _this.setState({
                  message: ''
                });
              }, 1000);
            });
          } else {
            _this.setState({
              message: message
            }, () => {
              setTimeout(() => {
                _this.setState({
                  message: ''
                });
              }, 1000);
            });
          }
        }
      })
      .catch(function (error) {
        if (_this.ismounted) {
          console.log(error);
          _this.setState({
            message: '请求失败,请稍后再试'
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      });
  }
  onChangeRadio = (e) => {
    var networkName = this.props.invitationdata ? this.props.invitationdata.networkName : this.props.changeNetwork;
    var data = {
      orgId: this.props.changeOrgid,
      networkName: networkName,
      openStatus: e.target.value == 1 ? 0 : 1
    };
    const Token = localStorage.getItem('token');
    var _this = this;
    axios.post('/api/block/network/modifyNetworkOpenStatus', data, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token,
      }
    })
      .then(function (response) {
        var code = response.data.code;
        var message = statuscode[code];
        if (_this.ismounted) {
          if (statuscode[response.data.code] == undefined) code = '500';
          if (code == 200) {
            _this.setState({
              message: message,
              disabled: response.data.data.openStatus == 0 ? '' : 'disable',
              invitation: response.data.data.invitation
            }, () => {
              setTimeout(() => {
                _this.setState({
                  message: ''
                });
              }, 1000);
            });
          } else {
            _this.setState({
              message: message,
            }, () => {
              setTimeout(() => {
                _this.setState({
                  message: ''
                });
              }, 1000);
            });
          }
        }
      })
      .catch(function (error) {
        console.log(error);
        if (_this.ismounted) {
          _this.setState({
            message: '请求失败,请稍后再试'
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      });
    this.setState({
      value: e.target.value,
    });
  }

  render() {
    const { visible, onCancel } = this.props;
    return (
      <Modal
        visible={visible}
        title="邀请组织"
        onCancel={onCancel}
        footer={[null]}
        className="invitebox"
      >
        <div className="invitationBox">
          <div className="titleTips"><i>!</i>您可以在“审批记录”中查看对方申请进度。</div>
          <FormItem
            label="邀请状态"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <RadioGroup name="radiogroup" onChange={this.onChangeRadio} value={this.state.disabled ? 2 : 1}>
              <Radio value={1}>开放邀请</Radio>
              <Radio value={2}>关闭邀请</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            label="邀请码"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <div className="invitationCode">
              <em className="codetype">{this.state.invitation}</em>
              <span className="copyCode" onClick={this.copyUrl.bind(this, this.state.invitation)}>复制邀请码</span>
            </div>
          </FormItem>
          <p className="copyCodeTips">请您记录好邀请码，并发送给被邀请人。被邀请人可在“加入网络”中填写信息并提交加入申请。 <span className="copyCode copyurl" onClick={this.copyUrl.bind(this, window.location.href)}>复制“加入网络”链接</span></p>
        </div>
        <Button key="submit" type="primary" className="inviteBtnNet" disabled={this.state.disabled} onClick={this.InviteCode}>
          重新生成邀请码
        </Button>
        <Tips message={this.state.message} />
      </Modal>
    );
  }
}

export default connect((state) => {
  return { ...state };
})(Invite);
